package com.micro.ai.auth.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.auth.entity.AuditLog;
import com.micro.ai.auth.mapper.AuditLogMapper;
import com.micro.ai.auth.service.AuditLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 操作审计日志服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class AuditLogServiceImpl extends ServiceImpl<AuditLogMapper, AuditLog> implements AuditLogService {

    @Autowired
    private AuditLogMapper auditLogMapper;

    @Override
    public void recordAuditLog(AuditLog auditLog) {
        try {
            if (auditLog.getCreatedAt() == null) {
                auditLog.setCreatedAt(LocalDateTime.now());
            }
            auditLogMapper.insert(auditLog);
            log.debug("审计日志记录成功: action={}, resourceType={}, resourceId={}", 
                auditLog.getAction(), auditLog.getResourceType(), auditLog.getResourceId());
        } catch (Exception e) {
            log.error("审计日志记录失败: {}", e.getMessage(), e);
        }
    }

    @Override
    public IPage<AuditLog> getAuditLogPage(
            Page<AuditLog> page,
            String userId,
            String tenantId,
            String action,
            String resourceType,
            LocalDateTime startTime,
            LocalDateTime endTime) {
        return auditLogMapper.selectAuditLogPage(page, userId, tenantId, action, resourceType, startTime, endTime);
    }

    @Override
    public List<AuditLog> getRecentLogsByUserId(String userId, Integer limit) {
        return auditLogMapper.selectRecentLogsByUserId(userId, limit);
    }

    @Override
    public List<AuditLog> getLogsByResource(String resourceType, String resourceId) {
        return auditLogMapper.selectLogsByResource(resourceType, resourceId);
    }

    @Override
    public List<AuditLog> getOperationStats(String userId, String tenantId, LocalDateTime startTime, LocalDateTime endTime) {
        return auditLogMapper.selectOperationStats(userId, tenantId, startTime, endTime);
    }

    @Override
    public int cleanExpiredLogs(int days) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
        int count = auditLogMapper.deleteExpiredLogs(cutoffTime);
        log.info("清理过期审计日志完成: 清理{}天前的日志，共清理{}条记录", days, count);
        return count;
    }
}
